﻿using Newtonsoft.Json;
using Prism.Navigation.TabbedPages;
using TangReadyV1.Models;
using TangReadyV1.Services;
using TangReadyV1.ViewModels;
using SQLite;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Xamarin.Forms;

namespace TangReadyV1.Views
{
    public partial class PageUpload : ContentPage
    {
      


        private ServiceReferenceInsert.InsertXsjlClient insertClient = null;
        private ServiceReferenceReg.Service1Client cloudClient = null;

        List<CommonFS> aListFromTable ;

        ObservableCollection<SaleTable> obsSales = new ObservableCollection<SaleTable>();
        private List<SaleTable> listSales ;
        private bool bVisited = false;
        private int maxId = 0; //当前流水号
        public PageUpload()
        {
            InitializeComponent();
          //  platService = DependencyService.Get<IWebService>();
          //  cloudService = DependencyService.Get<ICloudService>();

            ((PageUploadViewModel)BindingContext).IsActiveChanged += PageUpload_IsActiveChangedAsync;

            this.curDate.Date = DateTime.Now;
            this.curTimer.Time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

            this.ent2.Value = 0.00;
            listToUpload.ItemsSource = obsSales;


            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
            Pull_normal_ZFFS_ToLocal(path);

            //   listCom.DataSource = App.globalList;
            listCom.DataSource = aListFromTable;

            listCom.DisplayMemberPath = "NAME";
            listCom.SelectedIndex = 0;
        }

        private void Pull_normal_ZFFS_ToLocal(string path)
        {
            using (SQLiteConnection con = new SQLiteConnection(path))
            {

                List<CommonFS> fromTable = con.Table<CommonFS>().Where(a =>a.IsChecked==true).ToList();
                if (fromTable != null)
                {
                    aListFromTable = fromTable.OrderBy(bb => bb.CODE).ToList();
                }
            }
        }


        private  void UpdateList()
        {
            if (listSales!=null)
            {
                listSales.ForEach(t => obsSales.Add(t));
            }

            // 待上传交易列表(交易数100 交易额220)
           this.dealSum.Text = "待上传交易列表(交易数 " + obsSales.Count + "  交易额 " + obsSales.Sum(b => b.XSJE) + ")";

        }


       

        string msg2;
        string retShop;
        string retMarket;

        private async void  PageUpload_IsActiveChangedAsync(object sender, System.EventArgs e)
        {
            
            if (((PageUploadViewModel)BindingContext).IsActive)
            {
                //  listCom.DataSource = App.globalList;
                //  this.Title = ((PageUploadViewModel)BindingContext).Title;
              
              //      this.entCashierNo.Text = App.sktNo;
                    this.entShop.Text = App.shopName;

                    this.entMarket.Text = App.marketName;
               //     this.entItemCode.Text = App.spCode;
                    this.ent2.Value=(decimal)0.0;

                    string t6 = App.bNormalOperation ? "（正式环境）" : "（测试环境）";


                    this.Title = ((PageUploadViewModel)BindingContext).Title + t6;


                #region 验证 权限
                {
                    string deviceIdentifier = DependencyService.Get<IDevice>().GetIdentifier();

                   // cloudService.ChangeUrl(App.CloudUrl);
                    //默认的test 
                    cloudClient = new ServiceReferenceReg.Service1Client(ServiceReferenceReg.Service1Client.EndpointConfiguration.BasicHttpBinding_IService1, App.CloudUrl+ @":8052/Service1.svc");

              
                  
                    //   if (cloudService.Exist(this.entCashierNo.Text, this.entShop.Text, this.entMarket.Text, this.entItemCode.Text, deviceIdentifier, DateTime.Now, out msg2)) //登记过
                    if (cloudClient.Exist(App.sktNo, this.entShop.Text, this.entMarket.Text, App.spCode, deviceIdentifier, DateTime.Now, out msg2, out retShop, out retMarket)) //登记过

                    {

                        this.entCashierNo.Text = App.sktNo;
                        this.entItemCode.Text = App.spCode;

                        //当前的时分秒
                        this.curTimer.Time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

                        var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
                        Pull_normal_ZFFS_ToLocal(path);
                        listCom.DataSource = aListFromTable;
                        //  listCom.SelectedIndex = 0;
                        if (aListFromTable==null)
                        {
                            listCom.SelectedItem = new CommonFS() { CODE=16,NAME="现金(不返款)"};
                        }
                        else
                        {
                            if (aListFromTable.Count==0)
                            {
                                List<CommonFS> aaaa = new List<CommonFS>() { new CommonFS() { CODE = 16, NAME = "现金(不返款)" }, };
                                listCom.DataSource = aaaa;
                                listCom.SelectedItem =aaaa[0] ;
                            }
                            else
                            {
                                listCom.SelectedItem = aListFromTable[0];
                            }
                        }
                     //   listCom.SelectedItem = aListFromTable[0];
                        using (SQLiteConnection con = new SQLiteConnection(path))
                        {
                       //     con.CreateTable<SaleTable>(); 
                       
                            listSales = con.Table<SaleTable>().ToList();  //                          
                        }
                        if (obsSales!=null)
                        {
                            obsSales.Clear();
                        }
                        UpdateList();                      

                      
                    }
                    else //跳转到ParamSetting页面 
                    {
                        //   DisplayAlert("提示", msg2, "OK!");

                        if (msg2== "ValidChangeUUID")
                        {

                        }

                        App.Cloud_RetMsg = msg2;
                     await   ((PageUploadViewModel)BindingContext)._navigationService.SelectTabAsync("PageParam");
                    }

                    await cloudClient.CloseAsync();
                    
                }
                #endregion

                if (obsSales.Count<1)
                {
                    this.btnSumbit.IsEnabled = false;
                }

            }
        }



        int refInt = 0;
        private void btnSumbit_Clicked(object sender, System.EventArgs e)
        {
            this.btnSumbit.IsEnabled = false;
           
            //   platService.ChangeUrl("http://180.168.153.8:6666");

            insertClient = new ServiceReferenceInsert.InsertXsjlClient(ServiceReferenceInsert.InsertXsjlClient.EndpointConfiguration.BasicHttpBinding_IInsertXsjl, App.WebServiceUrl+ "/InsertXsjl.svc");


            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
            using (SQLiteConnection con = new SQLiteConnection(path))
            {
                
                for (int i = 0; i < obsSales.Count; i++)
                {                  

                    var item = obsSales[i];
                    XSJL aRecord = new XSJL();

                    aRecord.SKTNO = item.SKTNO;
                    aRecord.JYSJ = item.JYSJ;
                    aRecord.JZRQ = item.JZRQ;

                    aRecord.XSJE = item.XSJE;
                    aRecord.XSJLC = new List<XSJLC>() { new XSJLC() { SKTNO = item.SKTNO, SPCODE = item.SPCODE, LSDJ = item.XSJE, XSSL = 1, XSJE = item.XSJE, ZKJE = 0, TCKT_INX = item.TCKT_INX, INX = "01", YHJE = "0", } };
                    aRecord.XSJLM = new List<XSJLM>() { new XSJLM() { SKTNO = item.SKTNO, SKFS = item.SKFS.Split(new char[] { '-' })[0], SKJE = item.XSJE.ToString(), } };

                    string tempStr = JsonConvert.SerializeObject(aRecord);

                    SaleTableFinished ss = JsonConvert.DeserializeObject<SaleTableFinished>(JsonConvert.SerializeObject(item));

                    string errMsg = string.Empty;

                
                    ServiceReferenceInsert.BfInterfaceResult xResult= insertClient.InsertXsjl(tempStr);

                    bool yy = xResult.IsSuccess;
                    if (yy)
                    {
                       
                        // 保存之前要查重
                        ss.Uploaded = "是";
                        ss.ResultMsg = "成功";
                        con.Insert(ss);  //                      
                        //从旧表中移除
                        App.MiTotalDatabase.DeleteItemAsync(item);                      
                      //  obsSales.Remove(item);

                        obsSales.RemoveAt(i);
                        i--;
                       
                    }
                    else      //该分支为模仿成功提交  
                    {
                        // errMsg  max 250  
                        item.ResultMsg = errMsg=xResult.Message;
                        item.Uploaded = "否";


;
                    }


                }



            }

            //更新统计
            this.dealSum.Text = "待上传交易列表(交易数 " + obsSales.Count + "  交易额 " + obsSales.Sum(b => b.XSJE) + ")";

            if (obsSales.Count>1)
            {
                this.btnSumbit.IsEnabled = true;
            }
            else
            {
                this.btnSumbit.IsEnabled = false;
            }
            
        }



        private void listCom_SelectionChanged(object sender, Syncfusion.XForms.ComboBox.SelectionChangedEventArgs e)
        {
          
        }

        private async void btnSave_Clicked(object sender, EventArgs e)
        {
           // btnSave.Focus();
            int te2 = 1;

            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TotalSalesSQLite.db3");
          
            using (SQLiteConnection con = new SQLiteConnection(path))
            {
          
                List<FlowTable> v1 = con.Table<FlowTable>().ToList();  //还必须处理补录的情况

                var bb2 = v1.Where(x => x.SellDate == this.curDate.Date.ToString("yyyyMMdd")).ToList().OrderBy(t =>t.MaxID).LastOrDefault();
               

                if (bb2 == null)
                {
                   
                }
                else
                {
                    te2 = bb2.MaxID + 1;
                  
                }
                this.DealNo.Text = this.curDate.Date.ToString("yyyyMMdd") + String.Format("{0:D4}", te2);

                this.curTimer.Time = new TimeSpan(DateTime.Now.Hour,DateTime.Now.Minute,DateTime.Now.Second); //更新当前时间时分秒部分

            SaleTable temp = new SaleTable();

            temp.JZRQ = this.curDate.Date.ToString("yyyy-MM-dd");
            temp.JYSJ = this.curDate.Date.ToString("yyyy-MM-dd")+" "+this.curTimer.Time.ToString("c");
            temp.JYSJ2 = Convert.ToDateTime(temp.JYSJ);
            temp.SKTNO = this.entCashierNo.Text;
             temp.SCF = App.bNormalOperation ? "正式" : "测试";
                //App.bNormalOperation ? "（正式环境）" : "（测试环境）";

                temp.XSJE = ((bool)this.Sell.IsChecked) ? (decimal)this.ent2.Value : -(decimal)this.ent2.Value;
            //    temp.XSJE = (decimal)this.ent2.Value;
            temp.JYBH = this.DealNo.Text;
            temp.TCKT_INX = te2;
            temp.INX = "01";

            temp.JYLX = ((bool)this.Sell.IsChecked) ? "销售" : "退款";
            temp.SPCODE = this.entItemCode.Text;
            // temp.Uploaded = "未上传";
            temp.Uploaded = "否";
            temp.ResultMsg = "待上传";
            

            if (Math.Abs(temp.XSJE)<(decimal)0.001)
            {
              await  DisplayAlert("提示", @"非法金额！输入数字后请按[换行]键或点击其余空白区域", "OK!");
              this.ent2.Focus();
              return;
            }
                if (this.listCom.SelectedItem == null )
                {
                    await DisplayAlert("提示", "非法的支付方式", "OK!");
                    this.listCom.Focus();
                    return;
                }
                temp.SKFS = (this.listCom.SelectedItem as CommonFS).CODE.ToString() + "--" + (this.listCom.SelectedItem as CommonFS).NAME;

                Console.WriteLine((this.listCom.SelectedItem as CommonFS).CODE.ToString());


                obsSales.Add(temp);

           await   App.MiTotalDatabase.SaveItemAsync(temp);  //存入数据库  待上传表

                //更新UI
                con.Insert(new FlowTable() { SellDate = this.curDate.Date.ToString("yyyyMMdd"), Sell2Date = this.curDate.Date, MaxID = te2 });
               

            }




            this.ent2.Value =(decimal) 0;
            //更新统计
            this.dealSum.Text = "待上传交易列表(交易数 " + obsSales.Count + "  交易额 " + obsSales.Sum(b => b.XSJE) + ")";

            if (obsSales.Count >= 1)
            {
                this.btnSumbit.IsEnabled = true;
            }

        }

        private void curDate_DateSelected(object sender, DateChangedEventArgs e)
        {
         //   this.DealNo.Text = this.curDate.Date.ToString("yyyyMMdd")  + String.Format("{0:D4}", maxId++);
        }

        private async void btnDelete_Clicked(object sender, EventArgs e)
        {
            if (this.listToUpload.SelectedItem!=null)
            {
                var selected = this.listToUpload.SelectedItem as SaleTable;
                obsSales.Remove(selected);
                await App.MiTotalDatabase.DeleteItemAsync(selected);
            }

            

            //更新统计
            this.dealSum.Text = "待上传交易列表(交易数 " + obsSales.Count + "  交易额 " + obsSales.Sum(b => b.XSJE) + ")";

            if (obsSales.Count == 0)
            {
                this.btnSumbit.IsEnabled = false;
            }

        }
    }
}
